<template>
  <div id="app" class="excode">
    <div class="search">
    <div class="selectOption">
              <el-button type="success" @click='addAdvertisers'> 添加兑换码</el-button>
    </div>
    </div>
    <!--兑换码页面列表-->
    <div class="contain_two" style="min-width: 675px;">
      <table class="table table-bordered">
        <thead>
          <tr>
            <th>
              <div class="">
                <span>#</span>
              </div>
            </th>
            <th class=""><span>兑换码</span></th>
            <th>
              <div class="">
                <span>奖励物品</span>
              </div>
            </th>

            <th><span>兑换码起止时间</span></th>

            <th class=""><span>兑换总数量</span></th>
            <th class=""><span>已兑换数量</span></th>
            <th class=""><span>兑换码状态</span></th>
            <th class=""><span>操作</span></th>
          </tr>
        </thead>
        <tbody id="staff_info" class="">
          <tr class="contLi" v-for="(list,index) in tableData">
            <td>
              <div class=""><span class="">{{index+1}}</span></div>
            </td>
            <td>
              <div class=""><span class="">{{list.code}}</span></div>
            </td>
            <td>
              <div class=""><span class="">{{list.dicName}}</span></div>
            </td>
            <td>
              <div class=""><span class="">{{list.startDate}} —— {{list.endDate}}</span></div>
            </td>
            <td>
              <div class=""><span class="">{{list.totalNumber}}</span></div>
            </td>
            <td>
              <div class=""><span class="">{{list.useNumber}}</span></div>
            </td>
            <td>
              <div class="">
                <span class="">{{list.state}}</span>
               </div>
            </td>
            <td class="">
              <el-button type="info" @click="edit(index)" :disabled="list.state == '已结束'">编辑</el-button>
              <el-button type="danger" @click="open2(index)">删除</el-button>
            </td>
          </tr>
        </tbody>
      </table>

      <div class="block pagination" v-show='nullContentPagination'>
        <el-pagination @current-change="handleCurrentChange" :current-page="currentPage" :page-size="10" layout="prev, pager, next, jumper"
          :total="total">
          </el-pagination>
      </div>
      <div class="nullContent" v-show='nullContent'>暂无数据</div>
    </div>
    <!--添加兑换码-->
    <div class="tankuang" v-show="adverShow">
      <div class="bomb" style="height:421px;">
        <div class="bomb_header">
          <p class="bomb_title">添加广告主</p>
          <span @click="closes"><img src="../../assets/images/icon_tanc_close@2x.png" width="10px" height="10"></span>
        </div>
        <div class="bomb_content" style="height: 272px;">
          <div class="half">
              <p class="fl">
              <span>兑换码：</span>
              <input type="text" v-model="redeemCode" placeholder="请输入兑换码（10个字符）" id="codename">
            </p>
            <p class="fr">
              <span>兑换码数量：</span>
              <input type="text" v-model="redeemNum" placeholder="请输入兑换码数量" id="">
            </p>
            <p class="fl">
              <span>发布时段：</span>
          <el-date-picker v-model="redeemStart" type="datetime" placeholder="兑换码开始时间" :editable='false'>
          </el-date-picker>
            </p>
            <p class="fr">
              <span style="margin-left: 25px;">至：</span>
               <el-date-picker v-model="redeemStrop" type="datetime" placeholder="兑换码结束时间" :editable='false'>
             </el-date-picker>
            </p>
            </div>
            <div class="clear"></div>
             <p>
              <span>奖励物品：</span>
            </p>
            <ul class="reward">
              <li><input type="checkbox" value="现金" name="" id="money_1" @click="check" ><span>现金</span><input v-model="money" v-show="xianjin" type="text" class="ninety money" maxlength="4"  onkeyup="this.value=this.value.replace(/[^0-9]/g,'')" onafterpaste="this.value=this.value.replace(/[^0-9]/g,'')" placeholder="奖品数量(单位:元)"></li>
              <li><input type="checkbox" value="经验" name="" id="exper_1" @click="checks" ><span>经验</span><input v-model="exper" v-show="integral" type="text" class="ninety integral" maxlength="3" onkeyup="this.value=this.value.replace(/[^0-9]/g,'')" onafterpaste="this.value=this.value.replace(/[^0-9]/g,'')" placeholder="奖品数量"></li>
              <li><input type="checkbox" value="双倍收益" name="" id="twomoney_1" ><span>双倍收益</span></li>
              <li><input type="checkbox" value="双倍经验" name="" id="twoexper_1" ><span>双倍经验</span></li>
            </ul>
            <div class="clear"></div>
        </div>
        <div class="bomb_footer">
          <input type="button" v-show="addcode" @click="codeedixbtn()" value="保存"> 
          <input type="button" v-show="editcode" @click="editsave()" value="保存"> 
          <input type="button"@click="cancels" value="取消">
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import {
  mapActions,
  mapState
} from 'vuex'
// 导入地址数据 
import addressData from '../../assets/js/addressData.js'
// 加载地址数据
function formatData(data) {
  return data
}
export default {
  name: 'excode',
  data() {
    return {   
      nullContent: false,
      nullContentPagination: true, 
      hbdetail:false,  
      advLink:'../../../static/img/icon_xinjian_picture@2x.png',
      advHomer:'',
      advTitle:'',
      total:0,
      currentPage: 1,
      value1: '',
      adverShow: false,
      tableData: [],
      lists: [],
      list:{},
      redeemCode:'',
      redeemNum:'',
      redeemStart:'',
      redeemStrop:'',
      money:'',
      exper:'',
      xianjin:false,
      integral:false,
      bianji:false,
      id:'',
      addcode:false,
      editcode:false,
    }
  },
  created: function () {
    this.excode(1)
  },
  methods: {
    check:function(){
      if($('#money_1').prop('checked') == true){
        this.xianjin = true
      }else{
        this.xianjin = false
      }
    },
    checks:function(){
      if($('#exper_1').prop('checked') == true){
        this.integral = true
      }else{
        this.integral = false
      }
    },
    uploads: function () {
      $("#logofiles").click();
    },
    cancels: function () {
      this.adverShow = false;
    },
    closes:function(){
      this.hbdetail = false
      this.adverShow = false
    },
    panduan() {
       var g = /^[1-9]*[1-9][0-9]*$/;
    var regs =new RegExp("[.\u3000-\u303F\uFF00-\uFFEF\u3400-\u4DBF`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？%+_]+");
    var reg =/^\d+$/;
    if (this.redeemCode == '') {
      this.$message('请输入兑换码');
        return false;
    } else if (this.redeemCode.length > 10) {
      this.$message('兑换码长度不能超过10位');
        return false;
    } else if (regs.test(this.redeemCode)) {
      this.$message('兑换码不可以有特殊字符');
        return false;
    }
    if(this.redeemCode.length == 6 && reg.test(this.redeemCode)){
      this.$message('兑换码长度不能为纯6位数字');
        return false;
    }
    if (this.redeemNum == null || this.redeemNum == "") {
      this.$message('请输入兑换码数量');
        return false;
    }
   if (!g.test(this.redeemNum)) {
            this.$message('兑换码数量只能为正整数')
            return false;
          }

    if (new Date(this.redeemStart).getTime()< new Date().getTime()) {
      this.$message('兑换码开始时间不能小于当前时间');
        return false;
    }
    if (new Date(this.redeemStart).getTime()> new Date(this.redeemStrop).getTime()) {
      this.$message('兑换码开始时间不能大于结束时间');
        return false;
    }
    if (this.redeemStart == null || this.redeemStart == "") {
      this.$message('兑换码开始时间不能为空');
        return false;
    }
    if (this.redeemStrop == null || this.redeemStrop == "") {
      this.$message('兑换码结束时间不能为空');
        return false;
    }

    if ($(".reward li input[type='checkbox']:checked").length < 1) {
      this.$message('请选择奖励物品');
        return false;
    } else {
        if ($("#money_1").prop("checked")) {
            if (this.money == "" || this.money == null) {
              this.$message('现金奖励金额不能为空');
                return false;
            }
            if(parseFloat(this.money)>10000){
              this.$message('现金奖励金额不能大于10000')
                return false;
            }
        }
        if ($("#exper_1").prop("checked")) {
            if (this.exper == "" || this.exper == null) {
              this.$message('经验奖励经验值不能为空')
                return false;
            }
        }
    }

    return true;
},
    // 点击添加兑换码按钮
    addAdvertisers:function(){
      this.adverShow = true
      $('.tankuang .bomb_title').text("添加兑换码")    
      $('#codename').attr('disabled',false)
      this.addcode = true
      this.editcode = false
      this.redeemCode = ''
      this.redeemNum = ''
      this.redeemStart = ''
      this.redeemStrop = ''
       $("#money_1").prop("checked", false);
      this.xianjin = false
      this.money =''
      $("#exper_1").prop("checked",false);
      this.integral = false
      this.exper =''
       $("#twomoney_1").prop("checked",false);
       $("#twoexper_1").prop("checked",false);
    },
    // 兑换码添加下的保存
    codeedixbtn(){
      if(this.panduan() == false){
        return
      }else{
      var list = {
            token:sessionStorage.token,
            code: this.redeemCode,//兑换码
            totalNumber: this.redeemNum,//兑换数量
            startDate: this.UnFormatDate(this.redeemStart),//开始时间
            endDate: this.UnFormatDate(this.redeemStrop),//结束时间
        };
        if ($("#money_1").prop("checked")) {
            list.money = this.money;//现金奖励
        }
        if ($("#exper_1").prop("checked")) {
            list.experience = this.exper;//经验奖励
        }
        if ($("#twomoney_1").prop("checked")) {
            list.doubleMon = true;//双倍收益
        } else {
        }
        if ($("#twoexper_1").prop("checked")) {
            list.doubleExp = true;//双倍经验
        } else {
        }
      this.codeedixbtnlist(list).then((data)=>{
        console.log(data)
          if(data.code == 200){
            this.cancels()
            this.excode(this.currentPage)
          }else{
            this.$message('添加兑换码失败')
          }
      }).catch(msg => console.log(msg))
      }
    },
    // 兑换码页面 编辑  
    edit(index){
      console.log(index)
     this.adverShow = true
     $('#codename').attr('disabled',true)
      $('.tankuang .bomb_title').text("修改兑换码")    
      this.editcode = true
      this.addcode = false
      this.redeemCode = this.tableData[index].code
      this.redeemNum = this.tableData[index].totalNumber
      this.redeemStart = this.tableData[index].startDate
      this.redeemStrop = this.tableData[index].endDate
      this.id = this.tableData[index].id
      console.log(this.id)
      var dictionaries = ''
      for (var i = 0; i < this.tableData[index].dictionaries.length; i++) {
        dictionaries += this.tableData[index].dictionaries[i].dicType;
    }
    console.log(dictionaries)
    if (dictionaries.indexOf(1) >= 0) {
        $("#money_1").prop("checked", true);
        this.xianjin = true
        for (var m = 0; m < this.tableData[index].dictionaries.length; m++) {
            if (this.tableData[index].dictionaries[m].dicType == '1') {
                this.money = this.tableData[index].dictionaries[m].amount
            }
        }
    }else{
      $("#money_1").prop("checked", false);
      this.xianjin = false
      this.money =''
    }
    if (dictionaries.indexOf(2) >= 0) {
        $("#exper_1").prop("checked",true);
        this.integral = true
        for (var l = 0; l < this.tableData[index].dictionaries.length; l++) {
            if (this.tableData[index].dictionaries[l].dicType == '2') {
                this.exper = this.tableData[index].dictionaries[l].amount
            }
        }
    }else{
       $("#exper_1").prop("checked",false);
      this.integral = false
      this.exper =''
    }
    if (dictionaries.indexOf(3) >= 0) {
        $("#twomoney_1").prop("checked",true);
    }else{
       $("#twomoney_1").prop("checked",false);
    }
    if (dictionaries.indexOf(4) >= 0) {
        $("#twoexper_1").prop("checked",true);
    }else{
        $("#twoexper_1").prop("checked",false);
    }
  },
  // 编辑下的保存按钮
    editsave(){
      if(this.panduan() == false){
        return
      }else{
     var shuju = {
            token:sessionStorage.token,
            code: this.redeemCode,//兑换码
            totalNumber: this.redeemNum,//兑换数量
            startDate: this.UnFormatDate(this.redeemStart),//开始时间
            endDate: this.UnFormatDate(this.redeemStrop),//结束时间
            id:this.id
        };
         if ($("#money_1").prop("checked")) {
            shuju.money = this.money;//现金奖励
        }
        if ($("#exper_1").prop("checked")) {
            shuju.experience = this.exper;//经验奖励
        }
        if ($("#twomoney_1").prop("checked")) {
            shuju.doubleMon = true;//双倍收益
        } else {
        }
        if ($("#twoexper_1").prop("checked")) {
            shuju.doubleExp = true;//双倍经验
        } else {
        }
    this.editsavelist(shuju).then((data)=>{
      if(data.code == 200){
            console.log(data,'1211')
            this.cancels()
            this.excode(this.currentPage)
          }else{
            this.$message(data.message)
          }
    })
      }
    },

    
    // 获取兑换码页面数据
    excode(i) {
      this.$store.commit('showLoading');
      let token = sessionStorage.token;
      this.excodelist({
        delFlag:0,
        pageSize: 10,
        pageNo: i,
        token: token,
        jsonFilter:JSON.stringify({delFlag:0})
      }).then((data) => {
        this.$store.commit('hiddenLoading');
        console.log(data);
        if (data.code === 200) {
          this.nullContent = false;
          this.nullContentPagination = true;
          if (data.data.list.length == 0) {
              this.nullContent = true;
              this.nullContentPagination = false;
              return;
          }
          this.total = data.data.count;
          for (let i = 0; i < data.data.list.length; i++) {
            data.data.list[i].code = data.data.list[i].code;
            data.data.list[i].dicName = data.data.list[i].dictionaries[0].dicName;
            data.data.list[i].startDate = this.formatDate(data.data.list[i].startDate);
            data.data.list[i].endDate = this.formatDate(data.data.list[i].endDate);
            data.data.list[i].totalNumber = data.data.list[i].totalNumber;
            data.data.list[i].useNumber = data.data.list[i].useNumber;
            if(data.data.list[i].state == '3'){
              data.data.list[i].state = '已结束'
            }else if(data.data.list[i].state == '2'){
              data.data.list[i].state = '已开始'
            }else if(data.data.list[i].state == '1'){
              data.data.list[i].state = '未开始'
            }
          }
          this.tableData = data.data.list;
        } else {
          this.$message(data.message)
        }
      }).catch(msg => console.log(msg));
    },
    // 兑换码页面删除
    excodeDel(i){
      this.excodeDellist({
        id:this.tableData[i].id,
        token:sessionStorage.token
      }).then((data)=>{
        console.log(data)
        if (data.code === 200) {
            this.excode(this.currentPage)
        } else {
            this.$message('删除失败')
        }
      }).catch(msg => console.log(msg));     
    },
    open2(index) {
      console.log(index)
      console.log(this.tableData[index].id)
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
         this.excodeDel(index)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },
    
    
    // 格式化日期
    formatDate(date){
      var y,m,d,h,i,s
      var t = new Date(parseInt(date))
      y = t.getFullYear()
      m = t.getMonth() + 1
      d = t.getDate()
      h = t.getHours()
      i = t.getMinutes()
      s = t.getSeconds()
return y + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d) + ' '
            + (h < 10 ? '0' + h : h) + ':'+ (i < 10 ? '0' + i : i) + ':'+ (s < 10 ? '0' + s : s) 
    },
    // 请求格式化日期
    UnFormatDate(date) {
      var y,m,d,h,i
      var t = new  Date(date)
        y = t.getFullYear()
        m = t.getMonth() + 1
        d = t.getDate()
        h = t.getHours()
        i = t.getMinutes()
 return y + '/' + (m < 10 ? '0' + m : m) + '/' + (d < 10 ? '0' + d : d) + ' '
                + (h < 10 ? '0' + h : h) + ':'+ (i < 10 ? '0' + i : i) 

      },
    // 分页跳转
    handleCurrentChange(val) {
        this.currentPage = val;
        this.excode(val);
    },
    
...mapActions(['excodelist','excodeDellist','codeedixbtnlist','editsavelist'])

  }
}

</script>
<style scoped>
.fr>.el-date-editor{
  margin-left: 45px!important;
}
.el-button--success{
  width: 96px;
  margin-top: 2px;
}
  
  .add_reward {
    background: rgb(82, 186, 130);
    border-radius: 5px;
    width: 115px;
    height: 36px;
    border: none;
    margin-left: 45px;
    color: #fff;
  }
  
  th,
  td {
    text-align: center;
  }
  
  .contain_two {
    margin-top: 15px;
  }
  
  .tankuang {
    background: rgba(0, 0, 0, 0.5);
    position: fixed;
    overflow: auto;
    z-index: 1500;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 100%;
  }
  
  .bomb_content p {
    text-align: left;
    margin: 10px 0;
  }
  
  .bomb_content input[type=text] {
    width: 160px;
    height: 36px;
    margin-left: 13px;
    border-radius: 4px;
    border: 1px solid #bfcbd9;
  }
 ::-webkit-input-placeholder {
    color:#bfcbd9;  
}  
　　
  
  .bomb_content input[type=file] {
    display: none
  }
  
  .bomb_content img {
    margin-left: 8px;
  }
  
  .egRatio {
    width: 50%;
    top: 0;
    left: 201px;
    position: absolute;
    color: #a5a3a3;
  }
  
  .modal-footer {
    text-align: center;
  }
  
  .modal-footer button {
    margin: 0 8px;
  }
  
  .bomb_content .interest,
  .bomb_content .platform {
    display: inline-block;
    width: calc(100% - 107px);
  }
  
  .bomb_content .platform li,
  .interest li {
    text-align: left;
    width: 20%;
    float: left;
    padding: 8px 0;
  }
  
  h4 {
    border-bottom: 1px solid rgb(229, 229, 229);
    margin-bottom: 12px;
    margin-top: 10px;
    font-size: 2.2rem;
    font-weight: 300;
    text-align: left;
    line-height: 34px;
    padding-bottom: 10px;
  }
  
  .needmoney input {
    width: 50%;
  }
  
  .needmoney input[type=text] {
    width: 57%;
  }
  
  .browseunit input[type=text] {
    width: 31%;
  }
  .clickunit input[type=text] {
    width: 31%;
  }
  
  .dingxiang input[type=text] {
    width: 57%;
  }
  
  .interest li {
    width: 20%;
    float: left;
    padding: 10px 0;
  }
  .moneydafault p{
    float: left;
    margin: 0 10px;
    width:30%;
  }
  .moneydafault p input[type=text]{
    width:60%;
  }
  .fl{
    width: 50%;
    float: left;
    text-align: left;
    padding-left: 15px;
  }
  .fr{
    width: 50%;
    float: right;
    text-align: left;
  }
  .modal-detail{
    margin-top: 89px;
  }
  .modal-detail p{
    font-size: 16px;
    margin:10px 0;
  }
  .modal-detail p:nth-of-type(1){
    width: 100%;
    text-align: left;
    padding-left: 15px;
    margin: 3px 0;
    padding-top: 4px;
  }
  #ad_queue{
    margin:10px 0;
  }
  #ad_queue span{
    font-size: 16px;
  }
  .half p{
    padding-left:0;
  }
  .el-date-editor{
    margin-left:1px!important;
}
.reward li input[type=text]{
width:160px;
margin-left: 6px;
height: 30px;
}
.reward li span{
  margin-left:5px;
  line-height: 30px;
}
.reward li{
  text-align: left;
  float:left;
  width:50%;
  margin: 10px 0;
}
 table th{
    padding:0;
    height: 40px;
    line-height: 40px;
}
.table > tbody > tr{
    padding:0;
}
/*.table thead{
  background-color: #eef1f6;
}*/
.excode{
   width: 100%;
    height: 100%;
    background-color: #fff;
    border-radius: 5px;
}
input[type=checkbox]{
    margin: 8px 0 0;
}
.bomb_footer input:nth-child(1) {
    background: #3C5570;
  }
  .bomb_footer input:nth-child(2) {
    background: #3C5570;
  }
  .bomb_footer input:nth-child(3) {
    background: #DDDDDD;
  }
</style>
